namespace ScrumSprintMonitor.UI.Wpf
{
	#region #using Directives

	using System;
	using System.Windows;
	using System.Windows.Controls;

	#endregion

	public class AnimatedStackPanel : StackPanel
	{
		// Using a DependencyProperty as the backing store for Duration.  This enables animation, styling, binding, etc...
		public static readonly DependencyProperty DurationProperty = DependencyProperty.Register("Duration", typeof(Duration), typeof(AnimatedStackPanel),
		                                                                                         new UIPropertyMetadata(
		                                                                                         	new Duration(new TimeSpan(0, 0, 0, 0, 500))));

		public Duration Duration
		{
			get { return (Duration) GetValue(DurationProperty); }
			set { SetValue(DurationProperty, value); }
		}

		/// <summary>
		/// Arranges the content of a <see cref="T:System.Windows.Controls.StackPanel"/> element.
		/// </summary>
		/// <returns>
		/// The <see cref="T:System.Windows.Size"/> that represents the arranged size of this <see cref="T:System.Windows.Controls.StackPanel"/> element and its child elements.
		/// </returns>
		/// <param name="arrangeSize">The <see cref="T:System.Windows.Size"/> that this element should use to arrange its child elements.
		///                 </param>
		protected override Size ArrangeOverride(Size arrangeSize)
		{
			var children = base.Children;
			bool horizontal = Orientation == Orientation.Horizontal;
			var finalRect = new Rect(arrangeSize);
			double width = 0.0;
			int childIndex = 0;
			int count = children.Count;
			var duration = Duration;
			while (childIndex < count)
			{
				var element = children[childIndex];
				if (element != null)
				{
					if (horizontal)
					{
						finalRect.X += width;
						width = element.DesiredSize.Width;
						finalRect.Width = width;
						finalRect.Height = Math.Max(arrangeSize.Height, element.DesiredSize.Height);
					}
					else
					{
						finalRect.Y += width;
						width = element.DesiredSize.Height;
						finalRect.Height = width;
						finalRect.Width = Math.Max(arrangeSize.Width, element.DesiredSize.Width);
					}
					AnimatedPanelHelper.ArrangeChild(this, element, finalRect, duration);
				}
				childIndex++;
			}
			return arrangeSize;
		}
	}
}